import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadDemo2 {

    static class Worker extends Thread{
        private BlockingQueue<Runnable> queue = null;

        public Worker(BlockingQueue<Runnable> queue){
            this.queue = queue;
        }
        @Override
        public void run() {
            while (true){
                try {
                    Runnable command = queue.take();
                    command.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class ThreadPool{
        // 阻塞队列 用来组织任务
        private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

        // 用来存放当前的工作线程
        private List<Worker> workers = new ArrayList<>();

        // 最大工作线程数
        private final int MAX_WORKER_COUNT = 10;
        public void submit(Runnable command) throws InterruptedException {
            if(workers.size() < MAX_WORKER_COUNT){
                // 当前工作线程不足 创建新的线程
                // Worker内部需要获取到队列的内容,就需要创建一个构造方法.
                Worker worker = new Worker(queue);
                worker.start();
                workers.add(worker);
            }
            queue.put(command);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadPool pool = new ThreadPool();
        pool.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        });
    }
}
